package com.rcl.mvvmdemo.player

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import com.rcl.mvvmdemo.R
import com.rcl.mvvmdemo.base.BaseActivity
import com.rcl.mvvmdemo.musicList.MusicsPresenter
import kotlinx.android.synthetic.main.activity_player.*

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/11/4.
 * PS: Not easy to write code, please indicate.
 */
class PlayerActivity : BaseActivity() {

    private val playerPresenter by lazy {
        PlayerPresenter.instance
    }

    private val musicsPresenter by lazy {
        MusicsPresenter(this)
    }

    private lateinit var mLivePlayerStateObserver: LivePlayerStateObserver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player)

        initListener()
        initDataListener()
    }

    override fun onDestroy() {
        super.onDestroy()
        LivePlayerState.instance.removeObserver(mLivePlayerStateObserver)
    }

    inner class LivePlayerStateObserver : Observer<PlayerPresenter.PlayState> {
        override fun onChanged(t: PlayerPresenter.PlayState?) {
            Log.i("aaaaa", "播放器界面...live data -->当前状态-->$t")
        }
    }

    /**
     * 对数据进行监听
     */
    private fun initDataListener() {
        mLivePlayerStateObserver = LivePlayerStateObserver()
        LivePlayerState.instance.observeForever(mLivePlayerStateObserver)
        playerPresenter.currentMusic.addListener(this) {
            //音乐内容发生变化，更新UI
            songTitle?.text = it?.name
            println("封面改变了...${it?.cover}")
        }
        playerPresenter.currentPlayState.addListener(this) {
            when (it) {
                PlayerPresenter.PlayState.PAUSE -> {
                    playerOrPauseBtn?.text = "播放"
                }

                PlayerPresenter.PlayState.PLAYING -> {
                    playerOrPauseBtn?.text = "暂停"
                }
            }
        }
    }

    /**
     * 给控件设置相关事件
     */
    private fun initListener() {
        //播放按钮
        playerOrPauseBtn.setOnClickListener {
            //调用Presenter层的播放和暂停方法
            playerPresenter.doPlayOrPause()
        }
        //下一首按钮
        playNextBtn.setOnClickListener {
            playerPresenter.playNext()
        }
        //上一首按钮
        playPreBtn.setOnClickListener {
            playerPresenter.playPre()
        }
    }

    fun toFlowPage(view: View) {
        startActivity(Intent(this, FlowPlayerControllerActivity::class.java))
    }
}